package bme.andraskindler.treenventory.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import bme.andraskindler.treenventory.R;
import bme.andraskindler.treenventory.fragment.NewTypeDialogFragment;
import bme.andraskindler.treenventory.provider.TypeListAdapter;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

/**
 * 
 * @author andraskindler
 *
 * Fatípus megadására szolgáló activity. Egy listát jelent meg a már tárolt típusokról, mely rendezhető és kereshető. Létrehozhatunk új típust is, ekkor latin és magyar nevet kell megadni.
 */
public class TreeTypeActivity extends SherlockFragmentActivity {

	private TypeListAdapter mAdapter;

	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);

		final View v = getLayoutInflater().inflate(R.layout.activity_treetype, null);
		setContentView(v);

		final EditText searchEditText = (EditText) v.findViewById(R.id.treetype_search_text);

		(findViewById(R.id.treetype_search)).setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				final String query = searchEditText.getText().toString();
				mAdapter.search(query);
			}
		});

		final ListView list = (ListView) v.findViewById(R.id.treetype_list);
		mAdapter = new TypeListAdapter();
		list.setAdapter(mAdapter);

		list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				final String type = mAdapter.getItem(arg2).getHun();
				Intent returnIntent = new Intent();
				returnIntent.putExtra("result", type);
				setResult(RESULT_OK, returnIntent);
				finish();
			}
		});

		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menu_treetype, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_add:
			NewTypeDialogFragment.newInstance().show(getSupportFragmentManager(), "fragment_newtype_dialog");
			return true;
		case R.id.menu_sort_language:
			item.setTitle(mAdapter.isSortHungarian() == true ? getResources().getString(R.string.treetype_latin) : getResources().getString(R.string.treetype_hungarian));
			mAdapter.toggleSortHungarian();
			return true;
		case android.R.id.home:
			finish();
			return true;
		default:
			break;
		}
		return true;
	}

	public void refreshList() {
		mAdapter.notifyDataSetChanged();
	}

}
